<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue聊天室</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
    <!-- 验证页面 -->
    <div class="container" v-if="currentPage === 'auth'">
        <div class="auth-container">
            <h1>欢迎进入聊天室</h1>
            <div class="input-group">
                <input type="text" v-model="authToken" placeholder="请输入AuthToken" @keyup.enter="enterChatRoom">
                <button @click="enterChatRoom">进入聊天室</button>
            </div>
        </div>
    </div>

    <!-- 聊天页面 -->
    <div class="container" v-if="currentPage === 'chat'">
        <div class="chat-container">
            <div class="chat-header">
                <h2>聊天室 (admin)</h2>
            </div>
            <div class="messages" ref="messagesContainer">
                <div v-for="(msg, index) in messages" :key="index"
                     :class="['message', msg.type === 'system' ? 'system-message' : msg.type]">
                    {{ msg.content }}
                </div>
            </div>
            <div class="message-input">
                <input type="text" v-model="currentMessage" placeholder="输入消息..."
                       @keyup.enter="sendMessage" autocomplete="off">
                <button @click="sendMessage">发送</button>
            </div>
        </div>
    </div>

    <!-- 创建房间确认模态框 -->
    <div class="modal" v-if="showRoomModal">
        <div class="modal-content">
            <h3>聊天室不存在</h3>
            <p>聊天室暂时不存在，是否创建新聊天室？</p>
            <div class="modal-buttons">
                <button class="btn-cancel" @click="cancelCreateRoom">取消</button>
                <button @click="createRoomAndConnect">创建</button>
            </div>
        </div>
    </div>
</div>

<script>
    const {createApp, ref, onMounted, nextTick} = Vue;

    createApp({
        setup() {
            // 状态管理
            const currentPage = ref('auth');
            const authToken = ref('');
            const currentMessage = ref('');
            const showRoomModal = ref(false);
            const messages = ref([]);
            const socket = ref(null);
            const connectionTimeout = ref(null);
            const messagesContainer = ref(null);

            // 进入聊天室
            const enterChatRoom = () => {
                if (!authToken.value.trim()) {
                    alert('请输入AuthToken');
                    return;
                }
                currentPage.value = 'chat';
                connectWebSocket();
            };

            const connectWebSocket = () => {
                addSystemMessage('正在连接聊天室...');

                // 设置10秒超时
                connectionTimeout.value = setTimeout(() => {
                    if (!socket.value || socket.value.readyState !== WebSocket.OPEN) {
                        addSystemMessage('连接超时，聊天室可能不存在');
                        showRoomModal.value = true;
                        socket.value?.close(); // 确保关闭连接
                    }
                }, 10000);

                try {
                    socket.value = new WebSocket(`ws://123.207.11.78:8080/chat/admin?AuthToken=${encodeURIComponent(authToken.value)}`);

                    socket.value.onopen = (e) => {
                        clearTimeout(connectionTimeout.value);
                        addSystemMessage('已连接到聊天室');
                    };

                    socket.value.onerror = (error) => {
                        clearTimeout(connectionTimeout.value);
                        addSystemMessage('连接发生错误');
                        console.error('WebSocket错误:', error);
                        showRoomModal.value = true; // 显示创建房间弹窗
                    };

                    socket.value.onclose = (event) => {
                        clearTimeout(connectionTimeout.value);
                        if (event.wasClean) {
                            addSystemMessage(`房间号已关闭,请创建后使用!`);
                            showRoomModal.value = true;
                        } else {
                            addSystemMessage('连接中断');
                        }
                        // 如果不是用户主动关闭，显示创建房间弹窗
                        if (event.code !== 1000) {
                            showRoomModal.value = true;
                        }
                    };

                    socket.value.onmessage = (event) => {
                        try {
                            const data = JSON.parse(event.data);
                            const messageEntries = Object.entries(data);
                            messageEntries.forEach(([key, content]) => {
                                const [timestamp, username] = key.split('::');
                                const formattedMessage = `[${new Date(parseInt(timestamp)).toLocaleString()}] ${username}: ${content}`;
                                addMessage(formattedMessage, 'received');
                            });
                        } catch (e) {
                            addMessage(event.data, 'received');
                        }
                    };

                } catch (error) {
                    clearTimeout(connectionTimeout.value);
                    addSystemMessage('创建连接失败: ' + error.message);
                    showRoomModal.value = true;
                }
            };

            // 创建房间并重新连接 - 增强版
            const createRoomAndConnect = async () => {
                showRoomModal.value = false;
                addSystemMessage('正在创建聊天室...');

                try {
                    const response = await fetch('http://123.207.11.78:8080/function/simpleChat/createRoom', {
                        method: 'GET',
                        headers: {
                            'AuthToken': authToken.value
                        }
                    });

                    if (response.ok) {
                        addSystemMessage('聊天室创建成功，正在重新连接...');
                        // 关闭旧连接（如果存在）
                        if (socket.value) {
                            socket.value.close();
                            socket.value = null;
                        }
                        // 重新连接
                        connectWebSocket();
                    } else {
                        const errorText = await response.text();
                        throw new Error(errorText || '创建失败');
                    }
                } catch (error) {
                    addSystemMessage('创建聊天室失败: ' + error.message);
                    console.error('创建房间错误:', error);
                    // 创建失败后再次询问
                    showRoomModal.value = true;
                }
            };

            // 取消创建房间
            const cancelCreateRoom = () => {
                showRoomModal.value = false;
                currentPage.value = 'auth';
            };

            // 发送消息
            const sendMessage = async () => {
                const message = currentMessage.value.trim();
                if (!message) return;

                // 显示自己的消息
                // addMessage(message, 'sent');
                const headers = new Headers();
                headers.append('Content-Type', 'application/json');
                headers.append('AuthToken', authToken.value);

                try {
                    const response = await fetch('http://123.207.11.78:8080/function/simpleChat/sendMessageByRoomId', {
                        method: 'POST',
                        headers: headers,
                        body: JSON.stringify({
                            roomId: "admin",
                            message: message
                        })
                    });

                    if (!response.ok) {
                        throw new Error('发送失败');
                    } else {
                        currentMessage.value = '';
                    }
                } catch (error) {
                    addSystemMessage('消息发送失败: ' + error.message);
                    alert(error)
                }

            };

            // 添加消息
            const addMessage = (content, type) => {
                messages.value.push({content, type});
                scrollToBottom();
            };

            // 添加系统消息
            const addSystemMessage = (content) => {
                messages.value.push({content, type: 'system'});
                scrollToBottom();
            };

            // 滚动到底部
            const scrollToBottom = () => {
                nextTick(() => {
                    if (messagesContainer.value) {
                        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                    }
                });
            };

            return {
                currentPage,
                authToken,
                currentMessage,
                showRoomModal,
                messages,
                messagesContainer,
                enterChatRoom,
                sendMessage,
                cancelCreateRoom,
                createRoomAndConnect
            };
        }
    }).mount('#app');
</script>
<style>
    body {
        font-family: 'Arial', sans-serif;
        margin: 0;
        padding: 0;
        background-color: #f5f5f5;
        transition: all 0.3s;
    }

    .container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        flex-direction: column;
    }

    /* 验证页面样式 */
    .auth-container {
        background: white;
        padding: 2rem;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        width: 300px;
        text-align: center;
    }

    .input-group {
        margin-top: 1.5rem;
    }

    input {
        width: 100%;
        padding: 10px;
        margin-bottom: 1rem;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
    }

    button {
        width: 100%;
        padding: 10px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }

    button:hover {
        background-color: #45a049;
    }

    /* 聊天页面样式 */
    .chat-container {
        display: flex;
        flex-direction: column;
        height: 80vh;
        width: 90%;
        max-width: 800px;
        margin: 0 auto;
        border: 1px solid #ddd;
        border-radius: 8px;
        overflow: hidden;
        background-color: white;
    }

    .chat-header {
        padding: 1rem;
        background-color: #4CAF50;
        color: white;
        text-align: center;
    }

    .messages {
        flex: 1;
        padding: 1rem;
        overflow-y: auto;
        background-color: #f9f9f9;
    }

    .message-input {
        display: flex;
        padding: 1rem;
        background-color: white;
        border-top: 1px solid #ddd;
    }

    .message-input input {
        flex: 1;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        margin-right: 10px;
    }

    .message-input button {
        width: 180px;
        padding: 10px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }

    .message {
        margin-bottom: 10px;
        padding: 8px 12px;
        background-color: white;
        border-radius: 4px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        max-width: 70%;
        word-wrap: break-word;
    }

    .message.sent {
        margin-left: auto;
        background-color: #dcf8c6;
    }

    .message.received {
        margin-right: auto;
    }

    .system-message {
        text-align: center;
        color: #666;
        font-size: 0.9em;
        margin: 10px 0;
    }

    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    }

    .modal-content {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        width: 300px;
        text-align: center;
    }

    .modal-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
    }

    .modal-buttons button {
        width: 48%;
    }

    .btn-cancel {
        background-color: #f44336;
    }

    .btn-cancel:hover {
        background-color: #d32f2f;
    }
</style>
</body>
</html>
